package com.alm.token.ui.viewpagefragment;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Paint;
import android.net.http.SslError;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.RecyclerView;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alm.token.ConStant;
import com.alm.token.MyApp;
import com.alm.token.R;
import com.alm.token.apinew.AllApi;
import com.alm.token.apinew.BaseObserver;
import com.alm.token.base.BaseAdapter;
import com.alm.token.base.BaseViewPageFragment;
import com.alm.token.common.RefreshLoadMoreManager;
import com.alm.token.ui.activity.MainActivity;
import com.alm.token.ui.data.bean.HangQingMoreData;
import com.alm.token.ui.persenter.MyPreenter;
import com.alm.token.utils.CommonUtil;
import com.alm.token.utils.EmptyUtils;
import com.alm.token.utils.LanguageUtils;
import com.alm.token.utils.LogUtil;
import com.alm.token.utils.SpUtil;
import com.chad.library.adapter.base.BaseViewHolder;

import java.lang.reflect.Method;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

public class HangQingPageFrag extends BaseViewPageFragment implements MainActivity.MainActyHangQingLisenter {


    @BindView(R.id.title)
    TextView mtitle;
    //    @BindView(R.id.text_beginLoading)
//    TextView beginLoading;
//    @BindView(R.id.text_Loading)
//    TextView loading;
//    @BindView(R.id.text_endLoading)
//    TextView endLoading;
    @BindView(R.id.webView1)
    WebView mWebview;
    @BindView(R.id.loading_progress)
    ProgressBar progressBar;

    @BindView(R.id.recycler_view)
    RecyclerView recyclerView;
    @BindView(R.id.swipeRefreshLayout)
    SwipeRefreshLayout swipeRefreshLayout;
    @BindView(R.id.tv_clickreload)
    TextView tvClickreload;
    @BindView(R.id.nodatashow_body)
    RelativeLayout nodatashowBody;
    Retrofit retrofit;
    //    ApiService service;
    AllApi apiStores;
    private String id = "0", flag = "down", limit = "10";
    private int top_id = 0;
    private int bottom_id = 0;
    private RefreshLoadMoreManager<HangQingMoreData> manager;
    private List<HangQingMoreData> dataBeans = new ArrayList<>(), olddataBeans = new ArrayList<>();
    private Map<String, HangQingMoreData> maps = new HashMap<>();

    public String ticker = "BITFINEX:BTCUSD";

    public String BTCUSD_symbol = "BITFINEX:BTCUSD";
    public String ETHUSD_symbol = "BITFINEX:ETHUSD";
    public String XRPUSD_symbol = "BITFINEX:XRPUSD";
    public String EOSUSD_symbol = "BITFINEX:EOSUSD";
    public String LTCUSD_symbol = "BITFINEX:LTCUSD";
    public String BCHUSD_symbol = "BIKICOIN:BCHUSDT";
    public String TRXUSD_symbol = "BITFINEX:TRXUSD";
    public String DASHUSDT_symbol = "BITTREX:DASHUSDT";
    public String DOGEUSDT_symbol = "BITFOREX:DOGEUSDT";

    private List<String> tickers = new ArrayList<>();


    WebSettings mWebSettings;

    public static final int HANGQING = 1, FAXIAN = 2;
    private String url = "https://widget.lianxueqiu.com/market?apikey=161d7d03ee8fe9b2";

    public static HangQingPageFrag newInstance(int type) {
        HangQingPageFrag fragment = new HangQingPageFrag();
        Bundle args = new Bundle();
        args.putInt("type", type);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected MyPreenter initPreenter() {
        return null;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.viewpage_fragment_market;
    }

    @Override
    protected void initVariables() {
//        webview.loadUrl("https://www.baidu.com");

//        webview.loadUrl("https://widget.lianxueqiu.com/market/index.html?theme=THEME&ccy=CURRENCY");

        if ((int) getArguments().get("type") == HANGQING) {
            mtitle.setText(getString(R.string.market_hint_title));
            url = "https://widget.lianxueqiu.com/market?apikey=161d7d03ee8fe9b2&theme=light";
        } else {
            mtitle.setText(getString(R.string.findmore_hint_title));
            url = "https://cointelegraph.com/";
        }

        if (mtitle.getText().toString().equalsIgnoreCase(getString(R.string.findmore_hint_title))
                || (mtitle.getText().toString().equalsIgnoreCase(getString(R.string.market_hint_title))
                && SpUtil.getString(MyApp.context, ConStant.LANGAUE, "" + LanguageUtils.CHINESE_SIMPLE)
                .equalsIgnoreCase(LanguageUtils.CHINESE_SIMPLE))) {
            initWebView();
        } else {
            url = "https://widget.lianxueqiu.com/market?apikey=161d7d03ee8fe9b2&theme=light&language=en";
            initWebView();
//            initHangQingData();
//            loadMoreData(ticker);
        }
    }

    private void initHangQingData() {
        mWebview.setVisibility(View.GONE);
        progressBar.setVisibility(View.GONE);
        swipeRefreshLayout.setVisibility(View.GONE);
        nodatashowBody.setVisibility(View.VISIBLE);

        retrofit = new Retrofit.Builder()
                // 设置解析转换工厂
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                // 设置请求的域名
                .baseUrl("http://api.coindog.com")
                .build();
        apiStores = retrofit.create(AllApi.class);

        initManager();
        tvClickreload.setOnClickListener(this);

        tickers.add(BTCUSD_symbol);
        tickers.add(ETHUSD_symbol);
        tickers.add(XRPUSD_symbol);
        tickers.add(EOSUSD_symbol);
        tickers.add(LTCUSD_symbol);
        tickers.add(BCHUSD_symbol);
        tickers.add(TRXUSD_symbol);
        tickers.add(DASHUSDT_symbol);
        tickers.add(DOGEUSDT_symbol);


        for (int i = 0; i < tickers.size(); i++) {
            HangQingMoreData hangQingMoreData = new HangQingMoreData();
            hangQingMoreData.setFlag(i + 1);
            maps.put(tickers.get(i), hangQingMoreData);
        }
    }

    private void initWebView() {
        mWebview.setVisibility(View.VISIBLE);
        swipeRefreshLayout.setVisibility(View.GONE);
        nodatashowBody.setVisibility(View.GONE);

        mWebSettings = mWebview.getSettings();

        mWebview.getSettings().setBuiltInZoomControls(false);
        mWebview.getSettings().setJavaScriptEnabled(true);
        mWebview.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
        mWebview.getSettings().setBlockNetworkImage(true);

        mWebview.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        mWebview.getSettings().setAllowFileAccess(true);
        mWebview.getSettings().setAppCacheEnabled(true);
//        mWebview.getSettings().setPluginsEnabled(true);
        mWebview.getSettings().setSaveFormData(false);
//        mWebview.refreshPlugins(true);
        mWebview.getSettings().setLoadsImagesAutomatically(true);

        // http请求的时候，模拟为火狐的UA会造成实时公交那边的页面存在问题，所以模拟iPhone的ua来解决这个问题
        String user_agent =
                "Mozilla/5.0 (Macintosh; U; PPC Mac OS X; en) AppleWebKit/124 (KHTML, like Gecko) Safari/125.1";
        mWebview.getSettings().setUserAgentString(user_agent);

        /* Enable zooming */
        mWebview.getSettings().setSupportZoom(false);

//        mWebview.setBackgroundColor(getResources().getColor(R.color.white));

        mWebview.loadUrl(url);
        //设置不用系统浏览器打开,直接显示在当前Webview
        //设置WebViewClient类
        mWebview.setWebViewClient(new WebViewClient() {

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }

            //设置加载前的函数
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
//                System.out.println("开始加载了");
//                beginLoading.setText("开始加载了");
//                showWaitDialog();
                if (progressBar != null)
                    progressBar.setVisibility(View.VISIBLE);

            }

            //设置结束加载函数
            @Override
            public void onPageFinished(WebView view, String url) {
//                endLoading.setText("结束加载了");
//                hideWaitDialog();
                if (progressBar != null)
                    progressBar.setVisibility(View.GONE);
            }

            //webView默认是不处理https请求的，页面显示空白，需要进行如下设置：
            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                handler.proceed();    //表示等待证书响应
                // handler.cancel();      //表示挂起连接，为默认方式
                // handler.handleMessage(null);    //可做其他处理
            }

        });

        try {
            //禁用硬件加速
            Method method = WebView.class.getMethod("setLayerType", int.class, Paint.class);
            method.setAccessible(true);
            method.invoke(mWebview, 1, null);
        } catch (Exception e) {
            e.printStackTrace();
        }
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                mWebview.getSettings().setBlockNetworkImage(false);
            }
        }, 1000);


        //设置WebChromeClient类
        mWebview.setWebChromeClient(new WebChromeClient() {


            //获取网站标题
            @Override
            public void onReceivedTitle(WebView view, String title) {
//                System.out.println("标题在这里");
//                mtitle.setText(title);
            }


            //获取加载进度
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                if (progressBar != null)
                    progressBar.setProgress(newProgress);


//                if (newProgress < 100) {
//                    String progress = newProgress + "%";
//                    loading.setText(progress);
//                } else if (newProgress == 100) {
//                    String progress = newProgress + "%";
//                    loading.setText(progress);
//                }
            }
        });

    }

    private void initManager() {
        MessageAdapter adapter = new MessageAdapter(getActivity());
        manager = new RefreshLoadMoreManager.Builder(getActivity())
                .setAdapter(adapter)
                .setRecyclerView(recyclerView)
                .setSwipeRefreshLayout(swipeRefreshLayout)
                .setOnRefreshListener(new RefreshLoadMoreManager.OnRefreshListener() {
                    @Override
                    public void onRefresh() {
                        swipeRefreshLayout.setRefreshing(false);
//                        if(dataBeans.size()!=9){
//                            dataBeans.clear();
//                        }
                        showWaitDialog();
                        loadMoreData(ticker);
                    }
                })
                .setOpenLoadMore(true)
                .setOnLoadMoreListener(new RefreshLoadMoreManager.OnLoadMoreListener() {
                    @Override
                    public void onLoadMore() {
                        manager.getAdapter().loadMoreEnd(true);
                        manager.getAdapter().loadMoreFail();
//                        if(dataBeans.size()!=9){
//                            dataBeans.clear();
//                        }
                        showWaitDialog();
                        loadMoreData(ticker);

                    }
                })
                .build();
    }

    protected void loadMoreData(String ticker1) {
        apiStores.getHangQingMoreData(ticker1)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<HangQingMoreData>() {
                    @Override
                    protected void onSuccees(HangQingMoreData hangQingMoreData) throws Exception {
                        if (EmptyUtils.isNotEmpty(hangQingMoreData) && hangQingMoreData.getTicker() != null) {
                            LogUtil.e("hangQingMoreData=" + hangQingMoreData.toString());
                            hangQingMoreData.setLayoutId(MessageAdapter.LAYOUT_ID);
                            hangQingMoreData.setFlag(maps.get(hangQingMoreData.getTicker()).getFlag());
                            maps.put(hangQingMoreData.getTicker(), hangQingMoreData);

                            dataBeans.clear();
                            for (String key : maps.keySet()) {
                                HangQingMoreData data = maps.get(key);
                                if (data.getClose() != 0 && data.getBase() != null) {
                                    dataBeans.add(data);
                                }
                            }
                            Collections.sort(dataBeans);
//                        for (int i = 0; i < dataBeans.size(); i++) {
//                            if (dataBeans.get(i).getTicker().equalsIgnoreCase(hangQingMoreData.getTicker())) {
//                                dataBeans.get(i).setDegree(hangQingMoreData.getDegree());
//                                dataBeans.get(i).setClose(hangQingMoreData.getClose());
//                                break;
//                            }
//                        }

////                            if(flag!=0){
//                        dataBeans.add(tickers.indexOf(hangQingMoreData.getTicker()), hangQingMoreData);
////                            }else {
////                                dataBeans.add(hangQingMoreData);
////                            }


                            if (hangQingMoreData.getTicker().indexOf(DOGEUSDT_symbol) == -1) {
                                if (EmptyUtils.isEmpty(hangQingMoreData.getTicker())) {
                                    hangQingMoreData.setTicker(ticker1);
                                }
                                int lenth = tickers.indexOf(hangQingMoreData.getTicker());
                                loadMoreData(tickers.get(lenth < tickers.size() ? lenth + 1 : 0));
                            } else {
                                hideWaitDialog();
                            }
                        } else {
                            if (ticker1.indexOf(DOGEUSDT_symbol) == -1) {
                                int lenth = tickers.indexOf(ticker1);
                                loadMoreData(tickers.get(lenth < tickers.size() ? lenth + 1 : 0));
                            } else {
                                hideWaitDialog();
                            }
                        }


                        if (dataBeans != null && dataBeans.size() > 0) {
                            manager.setData(dataBeans);
                            swipeRefreshLayout.setVisibility(View.VISIBLE);
                            nodatashowBody.setVisibility(View.GONE);
                        } else {
                            swipeRefreshLayout.setVisibility(View.GONE);
                            nodatashowBody.setVisibility(View.VISIBLE);
                        }

                        //请求成功
//                        if (findMoreData.getCount() != 0 && findMoreData.getList() != null && findMoreData.getList().size() != 0) {
//                            if (top_id == 0) {//第一次
//                                top_id = findMoreData.getTop_id();
//                                bottom_id = findMoreData.getBottom_id();
//                                for (int i1 = 0; i1 < findMoreData.getList().size(); i1++) {
//                                    dataBeans.addAll(findMoreData.getList().get(i1).getLives());
//                                    if (dataBeans != null && dataBeans.size() != 0) {
//                                        for (int i = 0; i < dataBeans.size(); i++) {
//                                            dataBeans.get(i).setLayoutId(FindMorePageFrag.MessageAdapter.LAYOUT_ID);
//                                            dataBeans.get(i).setDate(findMoreData.getList().get(i1).getDate());
//                                        }
//                                    }
//                                }
//                            } else if (top_id < findMoreData.getTop_id()) {//刷新最新的数据 可能会重复
//
//                                for (int i1 = 0; i1 < findMoreData.getList().size(); i1++) {
//                                    List<FindMoreData.ListBean.LivesBean> beans = new ArrayList<>();
//                                    beans.addAll(findMoreData.getList().get(i1).getLives());
//                                    if (beans != null && beans.size() != 0) {
//                                        for (int i = beans.size() - 1; i >= 0; i--) {
//                                            beans.get(i).setLayoutId(FindMorePageFrag.MessageAdapter.LAYOUT_ID);
//                                            beans.get(i).setDate(findMoreData.getList().get(i1).getDate());
//                                            if (!dataBeans.contains(beans.get(i))) {
//                                                dataBeans.add(0, beans.get(i));
//                                            } else {
////                                                showToast("true");
//                                            }
//                                        }
//                                    }
//                                }
//
//                                top_id = findMoreData.getTop_id();
//                            } else if (bottom_id > findMoreData.getBottom_id()) {//加载的历史书籍
//                                for (int i1 = 0; i1 < findMoreData.getList().size(); i1++) {
//                                    List<FindMoreData.ListBean.LivesBean> beans = new ArrayList<>();
//                                    beans.addAll(findMoreData.getList().get(i1).getLives());
//                                    if (beans != null && beans.size() != 0) {
//                                        for (int i = beans.size() - 1; i >= 0; i--) {
//                                            beans.get(i).setLayoutId(FindMorePageFrag.MessageAdapter.LAYOUT_ID);
//                                            beans.get(i).setDate(findMoreData.getList().get(i1).getDate());
//                                        }
//                                    }
//                                    dataBeans.addAll(beans);
//                                }
//                                bottom_id = findMoreData.getBottom_id();
//                            }
//                            if (dataBeans != null && dataBeans.size() > 0) {
//                                manager.setData(dataBeans);
//                                swipeRefreshLayout.setVisibility(View.VISIBLE);
//                                nodatashowBody.setVisibility(View.GONE);
//                            } else {
//                                swipeRefreshLayout.setVisibility(View.GONE);
//                                nodatashowBody.setVisibility(View.VISIBLE);
//                            }
//                        }
                    }

                    @Override
                    protected void onFailure(Throwable e, boolean isNetWorkError) throws Exception {
//                            if(ticker1.indexOf(DOGEUSDT_symbol)==-1){
//                                int lenth=tickers.indexOf(ticker1);
//                                loadMoreData(tickers.get(lenth<tickers.size()?lenth+1:0));
//                            }

                        loadMoreData(ticker1);

                        hideWaitDialog();
//                            showToast(e.toString());
                        LogUtil.e(e.toString());
                    }
                });
    }

    @Override
    public boolean mainActyHangQing(MainActivity context, int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && mWebview.canGoBack()) {
            mWebview.goBack();
            return true;
        }

        return false;
    }

    @Override
    public void onDestroy() {
        if (mWebview != null) {
            mWebview.loadDataWithBaseURL(null, "", "text/html", "utf-8", null);
            mWebview.clearHistory();

            ((ViewGroup) mWebview.getParent()).removeView(mWebview);
            mWebview.destroy();
            mWebview = null;
        }
        super.onDestroy();
    }

    @Override
    protected void initViews(View view) {
    }

    @Override
    protected void loadData() {


    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_clickreload:
                loadMoreData(ticker);
                break;
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }


    public class MessageAdapter extends BaseAdapter<HangQingMoreData> {

        public static final int LAYOUT_ID = R.layout.item_marketlist_base;

        public MessageAdapter(@NonNull Context context) {
            super(context);
        }

        @Override
        protected void convert(BaseViewHolder helper, HangQingMoreData item, int itemType) {

            helper.setText(R.id.tv_base, helper.getPosition() + 1 + "\t\t" + item.getBase());
            helper.setText(R.id.tv_value, "$" + CommonUtil.saveToPoint2WithNo(item.getClose()));
            if (item.getDegree() < 0) {
//                helper.setTextColor(R.id.tv_degree,getResources().getColor(R.color.lehuobao_zhichu));
                helper.setText(R.id.tv_degree, CommonUtil.saveToPoint2WithNo(item.getDegree()) + "%");
                helper.setTextColor(R.id.tv_value, getResources().getColor(R.color.lehuobao_zhichu));
            } else {
//                helper.setTextColor(R.id.tv_degree,getResources().getColor(R.color.platform_color_wechat_circle));
                helper.setTextColor(R.id.tv_value, getResources().getColor(R.color.colorgreen1));
                helper.setText(R.id.tv_degree, "+" + CommonUtil.saveToPoint2WithNo(item.getDegree()) + "%");
            }
        }

    }
}